import 'dart:io';
import 'package:flutter/material.dart';
import 'package:record/record.dart';
import '../constants/app_theme.dart';
import '../constants/app_constants.dart';

/// 音频录制组件
/// 录音组件
class CustomAudioRecorder extends StatefulWidget {
  /// 录音文件路径
  final String? audioPath;
  
  /// 录音完成回调
  final Function(String path)? onRecordingComplete;
  
  /// 删除录音回调
  final VoidCallback? onDelete;
  
  /// 是否只读模式
  final bool readOnly;
  
  /// 最大录音时长（秒）
  final int maxDuration;

  const CustomAudioRecorder({
    super.key,
    this.audioPath,
    this.onRecordingComplete,
    this.onDelete,
    this.readOnly = false,
    this.maxDuration = AppConstants.maxRecordingDuration,
  });

  @override
  State<CustomAudioRecorder> createState() => _CustomAudioRecorderState();
}

class _CustomAudioRecorderState extends State<CustomAudioRecorder>
    with TickerProviderStateMixin {
  final AudioRecorder _recorder = AudioRecorder();
  
  bool _isRecording = false;
  bool _isPlaying = false;
  bool _isPaused = false;
  int _recordingDuration = 0;
  int _playbackPosition = 0;
  int _totalDuration = 0;
  
  late AnimationController _pulseController;
  late AnimationController _waveController;
  late Animation<double> _pulseAnimation;
  late Animation<double> _waveAnimation;
  
  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _initializeAudio();
  }

  @override
  void dispose() {
    _pulseController.dispose();
    _waveController.dispose();
    _recorder.dispose();
    super.dispose();
  }

  /// 初始化动画
  void _initializeAnimations() {
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    
    _waveController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _pulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.2,
    ).animate(CurvedAnimation(
      parent: _pulseController,
      curve: Curves.easeInOut,
    ));
    
    _waveAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _waveController,
      curve: Curves.easeInOut,
    ));
  }

  /// 初始化音频
  void _initializeAudio() async {
    if (widget.audioPath != null && File(widget.audioPath!).existsSync()) {
      // 获取音频时长
      // 这里需要使用音频播放器获取时长
      _totalDuration = 30; // 临时值
    }
  }

  /// 开始录音
  Future<void> _startRecording() async {
    try {
      // 检查权限
      if (await _recorder.hasPermission()) {
        final path = '${AppConstants.audioDirectory}/audio_${DateTime.now().millisecondsSinceEpoch}.m4a';
        
        await _recorder.start(
          const RecordConfig(
            encoder: AudioEncoder.aacLc,
            bitRate: 128000,
            sampleRate: 44100,
          ),
          path: path,
        );
        
        setState(() {
          _isRecording = true;
          _recordingDuration = 0;
        });
        
        // 开始动画
        _pulseController.repeat(reverse: true);
        _waveController.repeat();
        
        // 开始计时
        _startTimer();
      } else {
        _showError('需要录音权限');
      }
    } catch (e) {
      _showError('录音失败：$e');
    }
  }

  /// 停止录音
  Future<void> _stopRecording() async {
    try {
      final path = await _recorder.stop();
      
      setState(() {
        _isRecording = false;
      });
      
      // 停止动画
      _pulseController.stop();
      _waveController.stop();
      
      if (path != null && widget.onRecordingComplete != null) {
        widget.onRecordingComplete!(path);
      }
    } catch (e) {
      _showError('停止录音失败：$e');
    }
  }

  /// 开始播放
  Future<void> _startPlayback() async {
    if (widget.audioPath == null) return;
    
    try {
      // 这里需要使用音频播放器播放
      setState(() {
        _isPlaying = true;
        _isPaused = false;
      });
      
      // 开始播放动画
      _waveController.repeat();
    } catch (e) {
      _showError('播放失败：$e');
    }
  }

  /// 暂停播放
  Future<void> _pausePlayback() async {
    try {
      setState(() {
        _isPaused = true;
      });
      
      _waveController.stop();
    } catch (e) {
      _showError('暂停失败：$e');
    }
  }

  /// 停止播放
  Future<void> _stopPlayback() async {
    try {
      setState(() {
        _isPlaying = false;
        _isPaused = false;
        _playbackPosition = 0;
      });
      
      _waveController.stop();
    } catch (e) {
      _showError('停止播放失败：$e');
    }
  }

  /// 删除录音
  void _deleteRecording() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除录音'),
        content: const Text('确定要删除这段录音吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              if (widget.onDelete != null) {
                widget.onDelete!();
              }
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 开始计时
  void _startTimer() {
    Future.delayed(const Duration(seconds: 1), () {
      if (_isRecording) {
        setState(() {
          _recordingDuration++;
        });
        
        if (_recordingDuration >= widget.maxDuration) {
          _stopRecording();
        } else {
          _startTimer();
        }
      }
    });
  }

  /// 显示错误
  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  /// 格式化时间
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    if (widget.audioPath != null) {
      return _buildPlaybackWidget();
    } else {
      return _buildRecordingWidget();
    }
  }

  /// 构建录音组件
  Widget _buildRecordingWidget() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: _isRecording ? AppTheme.primaryColor : AppTheme.dividerColor,
          width: _isRecording ? 2 : 1,
        ),
      ),
      child: Column(
        children: [
          // 录音按钮
          _buildRecordButton(),
          
          const SizedBox(height: 16),
          
          // 录音时长
          if (_isRecording)
            _buildRecordingDuration(),
          
          // 波形动画
          if (_isRecording)
            _buildWaveAnimation(),
        ],
      ),
    );
  }

  /// 构建播放组件
  Widget _buildPlaybackWidget() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: Column(
        children: [
          // 播放控制
          _buildPlaybackControls(),
          
          const SizedBox(height: 12),
          
          // 进度条
          _buildProgressBar(),
          
          const SizedBox(height: 8),
          
          // 时间显示
          _buildTimeDisplay(),
        ],
      ),
    );
  }

  /// 构建录音按钮
  Widget _buildRecordButton() {
    return GestureDetector(
      onTap: widget.readOnly ? null : (_isRecording ? _stopRecording : _startRecording),
      child: AnimatedBuilder(
        animation: _pulseAnimation,
        builder: (context, child) {
          return Transform.scale(
            scale: _isRecording ? _pulseAnimation.value : 1.0,
            child: Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: _isRecording ? AppTheme.errorColor : AppTheme.primaryColor,
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: (_isRecording ? AppTheme.errorColor : AppTheme.primaryColor)
                        .withOpacity(0.3),
                    blurRadius: 20,
                    spreadRadius: _isRecording ? 10 : 5,
                  ),
                ],
              ),
              child: Icon(
                _isRecording ? Icons.stop : Icons.mic,
                color: Colors.white,
                size: 32,
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建录音时长显示
  Widget _buildRecordingDuration() {
    return Column(
      children: [
        Text(
          _formatDuration(_recordingDuration),
          style: const TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: AppTheme.primaryColor,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          '最长 ${_formatDuration(widget.maxDuration)}',
          style: TextStyle(
            fontSize: 12,
            color: AppTheme.textSecondaryColor,
          ),
        ),
      ],
    );
  }

  /// 构建波形动画
  Widget _buildWaveAnimation() {
    return AnimatedBuilder(
      animation: _waveAnimation,
      builder: (context, child) {
        return Container(
          height: 40,
          margin: const EdgeInsets.only(top: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(5, (index) {
              final delay = index * 0.2;
              final animationValue = (_waveAnimation.value + delay) % 1.0;
              final height = 10 + (animationValue * 20);
              
              return Container(
                width: 4,
                height: height,
                margin: const EdgeInsets.symmetric(horizontal: 2),
                decoration: BoxDecoration(
                  color: AppTheme.primaryColor,
                  borderRadius: BorderRadius.circular(2),
                ),
              );
            }),
          ),
        );
      },
    );
  }

  /// 构建播放控制
  Widget _buildPlaybackControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 播放/暂停按钮
        IconButton(
          onPressed: widget.readOnly ? null : (
            _isPlaying
                ? (_isPaused ? _startPlayback : _pausePlayback)
                : _startPlayback
          ),
          icon: Icon(
            _isPlaying && !_isPaused ? Icons.pause : Icons.play_arrow,
            size: 32,
          ),
          color: AppTheme.primaryColor,
        ),
        
        const SizedBox(width: 16),
        
        // 停止按钮
        if (_isPlaying)
          IconButton(
            onPressed: _stopPlayback,
            icon: const Icon(
              Icons.stop,
              size: 24,
            ),
            color: AppTheme.textSecondaryColor,
          ),
        
        const Spacer(),
        
        // 删除按钮
        if (!widget.readOnly)
          IconButton(
            onPressed: _deleteRecording,
            icon: const Icon(
              Icons.delete_outline,
              size: 24,
            ),
            color: AppTheme.errorColor,
          ),
      ],
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    final progress = _totalDuration > 0 ? _playbackPosition / _totalDuration : 0.0;
    
    return LinearProgressIndicator(
      value: progress,
      backgroundColor: AppTheme.dividerColor,
      valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
    );
  }

  /// 构建时间显示
  Widget _buildTimeDisplay() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          _formatDuration(_playbackPosition),
          style: TextStyle(
            fontSize: 12,
            color: AppTheme.textSecondaryColor,
          ),
        ),
        Text(
          _formatDuration(_totalDuration),
          style: TextStyle(
            fontSize: 12,
            color: AppTheme.textSecondaryColor,
          ),
        ),
      ],
    );
  }
}

/// 紧凑音频播放器
/// 用于在列表中显示音频
class CompactAudioPlayer extends StatelessWidget {
  /// 音频文件路径
  final String audioPath;
  
  /// 音频时长（秒）
  final int duration;
  
  /// 点击回调
  final VoidCallback? onTap;

  const CompactAudioPlayer({
    super.key,
    required this.audioPath,
    required this.duration,
    this.onTap,
  });

  /// 格式化时间
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: 12,
          vertical: 8,
        ),
        decoration: BoxDecoration(
          color: AppTheme.surfaceColor,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: AppTheme.dividerColor,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.play_arrow,
              color: AppTheme.primaryColor,
              size: 20,
            ),
            const SizedBox(width: 8),
            Icon(
              Icons.audiotrack,
              color: AppTheme.textSecondaryColor,
              size: 16,
            ),
            const SizedBox(width: 4),
            Text(
              _formatDuration(duration),
              style: TextStyle(
                fontSize: 12,
                color: AppTheme.textSecondaryColor,
              ),
            ),
          ],
        ),
      ),
    );
  }
}